package com.ruoyi.bargain.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.bargain.mapper.BargainRecordMapper;
import com.ruoyi.bargain.mapper.BargainRegistrationMapper;
import com.ruoyi.bargain.domain.Bargain;
import com.ruoyi.bargain.domain.BargainRecord;
import com.ruoyi.bargain.domain.BargainRegistration;
import com.ruoyi.bargain.service.IBargainRecordService;
import com.ruoyi.bargain.service.IBargainService;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.RandomUtils;

/**
 * 砍价帮砍记录 服务层实现
 * 
 * @author lzy
 * @date 2019-03-07
 */
@Service
public class BargainRecordServiceImpl implements IBargainRecordService 
{
	protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(BargainRecordServiceImpl.class);
	
	@Autowired
	private BargainRecordMapper bargainRecordMapper;
	@Autowired
	private IBargainService bargainService;
	@Autowired
	private BargainRegistrationMapper bargainRegistrationMapper;

	/**
     * 查询砍价帮砍记录信息
     * 
     * @param id 砍价帮砍记录ID
     * @return 砍价帮砍记录信息
     */
    @Override
	public BargainRecord selectBargainRecordById(String id)
	{
	    return bargainRecordMapper.selectBargainRecordById(id);
	}
	
	/**
     * 查询砍价帮砍记录列表
     * 
     * @param bargainRecord 砍价帮砍记录信息
     * @return 砍价帮砍记录集合
     */
	@Override
	public List<BargainRecord> selectBargainRecordList(BargainRecord bargainRecord)
	{
	    return bargainRecordMapper.selectBargainRecordList(bargainRecord);
	}
	
    /**
     * 新增砍价帮砍记录
     * 
     * @param bargainRecord 砍价帮砍记录信息
     * @return 结果
     */
	@Override
	public int insertBargainRecord(BargainRecord bargainRecord)
	{
	    return bargainRecordMapper.insertBargainRecord(bargainRecord);
	}
	
	/**
     * 修改砍价帮砍记录
     * 
     * @param bargainRecord 砍价帮砍记录信息
     * @return 结果
     */
	@Override
	public int updateBargainRecord(BargainRecord bargainRecord)
	{
	    return bargainRecordMapper.updateBargainRecord(bargainRecord);
	}

	/**
     * 删除砍价帮砍记录对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteBargainRecordByIds(String ids)
	{
		return bargainRecordMapper.deleteBargainRecordByIds(Convert.toStrArray(ids));
	}

	@Override
	public List<BargainRecord> queryBargainRecordListByRegistrationId(String id) {
		// TODO Auto-generated method stub
		return bargainRecordMapper.queryBargainRecordListByRegistrationId(id);
	}

	@Override
	public List<BargainRecord> queryBargainRecordListByRegistrationIdAndOpenid(String registrationId, String openid) {
		// TODO Auto-generated method stub
		return bargainRecordMapper.queryBargainRecordListByRegistrationIdAndOpenid(registrationId,openid);
	}


	
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public String bargain(BargainRegistration bargainRegistration,BargainRecord gzWxActBargainRecord) {
		String cutStatus = "first";
		Bargain gzWxActBargain = bargainService.selectBargainById(bargainRegistration.getActId());
		if(bargainRegistration.getProductNewPrice().compareTo(gzWxActBargain.getCutMinPrice())<=0){
			cutStatus = "cutMin";
			return cutStatus;
		}
		
		BigDecimal cutPrice = getCutPrice(gzWxActBargain.getActRule());
		Date currDate = new Date();
		if(currDate.after(gzWxActBargain.getEndTime())){
			/*throw new GzbargainException(GzbargainExceptionEnum.ACT_BARGAIN_END,"活动已结束");*/
			try {
				throw new Exception("活动已结束");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		BigDecimal lastprice=bargainRegistration.getProductNewPrice();//上一次的最新价格
		//更新报名砍价信息
		bargainRegistrationMapper.updateBargainPrice(gzWxActBargainRecord.getRegistrationId(), cutPrice);
		//获取报名信息
		bargainRegistrationMapper.selectBargainRegistrationById(gzWxActBargainRecord.getRegistrationId());
		if(bargainRegistration.getProductNewPrice().compareTo(gzWxActBargain.getCutMinPrice())<0){
			bargainRegistration.setProductNewPrice(gzWxActBargain.getCutMinPrice());
			bargainRegistrationMapper.updateBargainRegistration(bargainRegistration);
			cutPrice=lastprice.subtract(gzWxActBargain.getCutMinPrice());
			cutStatus = "last";
		}else if(bargainRegistration.getProductNewPrice().compareTo(gzWxActBargain.getCutMinPrice())==0){
			cutStatus = "last";
		}
		logger.info("update gzWxActBargainRecord after:{}", bargainRegistration);
		
		//插入砍价记录
		gzWxActBargainRecord.setId(RandomUtils.generateID());
		gzWxActBargainRecord.setCutPrice(cutPrice);
		gzWxActBargainRecord.setCurrPrice(lastprice.subtract(cutPrice));
		gzWxActBargainRecord.setCreateTime(new Date());
		gzWxActBargainRecord.setJwid(bargainRegistration.getJwid());
		logger.info("insert gzWxActBargainRecord:{}", gzWxActBargainRecord);
		bargainRecordMapper.insertBargainRecord(gzWxActBargainRecord);
		
		return cutStatus;
	}
	
	private BigDecimal getCutPrice(String actRule){
		try {
			String [] rules = actRule.split(",");
			if(rules.length==2){
				float min=Float.valueOf(rules[0]);
				float max=Float.valueOf(rules[1]);
			    BigDecimal db = new BigDecimal(Math.random() * (max - min) + min);  
			    return db.setScale(2, BigDecimal.ROUND_HALF_UP);
			}else if(rules.length==3){
				float min=Float.valueOf(rules[0]);
				float max=Float.valueOf(rules[1]);
			    BigDecimal db = new BigDecimal(Math.random() * (max - min) + min);  
			    return db.setScale(2, BigDecimal.ROUND_HALF_UP);
			}else{
				/*throw new GzbargainException(GzbargainExceptionEnum.ACT_BARGAIN_RULE_ERROR);*/
				return null;
			}
		} catch (Exception e) {
			/*throw new GzbargainException(GzbargainExceptionEnum.ACT_BARGAIN_RULE_ERROR);*/
			return null;
		}
	}
	
}
